package com.project.x.webserver;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.io.*;
import java.util.*;

import org.askerov.dynamicgrid.example.Cheeses;

import com.project.x.R;


public class Httpd extends Activity
{
    private WebServer server;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webserver);
        server = new WebServer();
        try {
            server.start();
        } catch(IOException ioe) {
            Log.w("Httpd", "The server could not start.");
        }
        Log.w("Httpd", "Web server initialized.");
    }


    // DON'T FORGET to stop the server
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (server != null) {
            server.stop();
            Log.w("Httpd", "Web server stopped.");
        }
    }

    private class WebServer extends NanoHTTPD {

        public WebServer()
        {
            super(8080);
        }

        @Override
        public Response serve(String uri, Method method, 
                              Map<String, String> header,
                              Map<String, String> parameters,
                              Map<String, String> files) {
            String answer = "";
            try {
                // Open file from SD Card            	
//                File root = Environment.getExternalStorageDirectory();
//                FileReader index = new FileReader(root.getAbsolutePath() +
//                        "/www/index.html");
//                BufferedReader reader = new BufferedReader(index);
                

            	InputStream is = getAssets().open("www/index.html");
            	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = "";
                while ((line = reader.readLine()) != null) {
                	if (line.equals("<body>")) {
                		Cheeses cheese = new Cheeses();
                		answer += "<h1> Cheeses From Around The World! </h1>";
                		for (int i=0; i<cheese.sCheeseStrings.length; i++)
                			answer += "<p> "+cheese.sCheeseStrings[i]+" </p>";
                	}
                    answer += line;
                }
                reader.close();

            } catch(IOException ioe) {
                Log.w("Httpd", ioe.toString());
            }


            return new NanoHTTPD.Response(answer);
        }
    }
}